package net.qunzhi.modules.ysweixin.service;

import net.qunzhi.modules.ysweixin.entity.AccessToken;
import net.qunzhi.modules.ysweixin.utils.WxUtils;
import net.sf.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class WxService {
	
	private static final String GET_TOKEN_URL ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	
//	private static final String APPID = "wxf9a443e56149361b";
	
//	private static final String APPSECRET = "5f1bfd6f032fed02b99dc73dec745208";

	private static final String TOKEN = "qunzhi2019";
	
	//用户存储token
	private static AccessToken at;
	
	/**
	 * 获取token 
	 */
	private static void getToken(String appId,String secret) {
		String url = GET_TOKEN_URL.replace("APPID", appId).replace("APPSECRET", secret);
		String tokenStr = WxUtils.get(url);
		JSONObject fromObject = JSONObject.fromObject(tokenStr);
		String token = fromObject.getString("access_token");
		String expiresIn = fromObject.getString("expires_in");
		//创建token对象，并存起来
		at = new AccessToken(token, expiresIn);
	}
	
	/**
	 * 获取accessToken
	 * @return
	 */
	public static String getAccessToken(String appId,String secret) {
		if (at == null||at.isExpired()) {
			getToken(appId,secret);
		}
		return at.getAccessToken();
	}
	
	
	/**
	 * 验证签名方法
	 */
	public static boolean checkSignature(String timestamp,String nonce,String signature) {
		// 1）将token、timestamp、nonce三个参数进行字典序排序
		String[] strs = new String[] {TOKEN,timestamp,nonce};
		Arrays.sort(strs);
		//  2）将三个参数字符串拼接成一个字符串进行sha1加密 
		String str = strs[0] + strs[1] + strs[2];
		String mysig = sha1(str);
		//  3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		if (signature.equals(mysig)) {
			return true;
		}
		return false;
	}
	private static  String sha1(String src) {
		//获取一个加密的对象
		try {
			MessageDigest md = MessageDigest.getInstance("sha1");
			//加密
			byte[] digest = md.digest(src.getBytes());
			char[] chars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
			StringBuilder sb = new StringBuilder();
			//处理加密结果
			for (byte b : digest) {
				sb.append(chars[(b>>4&15)]);
				sb.append(chars[b&15]);
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		return null;
		
	}
	/**
	 * 获取用户的信息
	 * @return
	 */
//	public static String getUserRoleListByOpenId(String openId) {
//		String at = WxService.getAccessToken();
//		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//		url = url.replace("ACCESS_TOKEN", at).replace("OPENID", openId);
//		String string = WxUtils.get(url);
//		return string;
//	}
}
